<template>
  <div class="login_container">
    <div class="login_box">
      <div class="avater_box">
        <img src="../assets/logo.png"/>
      </div>
      <!--表单-->
      <el-form class="login_form" :model="loginForm" :rules="loginRoles" ref="loginRef" label-width="0px">
        <el-form-item prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="iconfont icon-3702mima" v-model="loginForm.password" placeholder="请输入密码" type="password"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="login('loginRef')" type="primary">登录</el-button>
          <el-button @click="resetLoginForm('loginRef')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      /* 表单验证规则 */
      loginRoles: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 9, message: '长度在 5 到 9 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetLoginForm (formRefName) {
      this.$refs[formRefName].resetFields()
    },
    login (formRefName) {
      this.$refs[formRefName].validate(async vali => {
        if (vali) {
          const { data: res } = await this.$http.post('login', this.loginForm)
          if (res.meta.status === 200) {
            /*
             * 1，提示登录成功
             * 2，保存token到sessionStorage
             * 3，跳转页面到/home
             * */
            this.$message.success('登录成功')
            window.sessionStorage.setItem('token', res.data.token)
            await this.$router.push('/home')
          } else return this.$message.error('登录失败')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .login_container {
    background-color: #2b4b6b;
    height: 100%;
  }

  .login_box {
    height: 300px;
    width: 450px;
    background-color: #ffffff;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    .avater_box {
      height: 130px;
      width: 130px;
      border-radius: 50%;
      border: 1px solid #eeeeee;
      padding: 10px;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #ffffff;
      box-shadow: 0 0 10px #dddddd;

      img {
        height: 100%;
        width: 100%;
        border-radius: 50%;
        background-color: #eeeeee;
      }
    }

    .login_form {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 0 20px;
      box-sizing: border-box;
    }
  }
</style>
